package cn.smbms.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.smbms.dao.PermissionMapper;
import cn.smbms.dao.RoleMapper;
import cn.smbms.dao.RolePermissionMapper;
import cn.smbms.pojo.Permission;
import cn.smbms.pojo.Role;
import cn.smbms.pojo.RolePermission;
import cn.smbms.vo.ResultVo;
import cn.smbms.vo.TreeVo;
import tk.mybatis.mapper.entity.Example;

@RestController
@RequestMapping("jsp/")
public class RoleController {

	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private PermissionMapper permissionMapper;
	@Autowired
	private RolePermissionMapper rolePermissionMapper;

	@PostMapping("rolegrant")
	public ResultVo rolegrant(Integer roleid, Integer[] perms) {
		// 保存角色对应的权限信息
		RolePermission rolePermission = new RolePermission();
		rolePermission.setRoleId(roleid);
		rolePermissionMapper.delete(rolePermission);
		if (perms != null) {
			for (int i = 0; i < perms.length; i++) {
				rolePermission.setPermId(perms[i]);
				rolePermissionMapper.insert(rolePermission);
			}
		}
		return ResultVo.success("授权成功");
	}

	@RequestMapping("rolelist")
	public ResultVo rolelist(String roleName, Model model) {
		// List<Role> roleList = roleMapper.selectAll();
		Example example = new Example(Role.class);
		if (roleName != null && !"".equals(roleName)) {
			example.createCriteria().andLike("roleName", "%" + roleName + "%");
		}
		List<Role> roleList = roleMapper.selectByExample(example);
		model.addAttribute("roleList", roleList);
		return ResultVo.success(roleList);
	}

	@GetMapping("permissions/{roleid}")
	public ResultVo permissions(@PathVariable Integer roleid) {
		List<TreeVo> treeList = new ArrayList<>();
		List<Permission> permList = permissionMapper.selectAll();
		List<Permission> userPermList = roleMapper.getPermissionByRoleId(roleid);
		permList.stream().forEach((perm) -> {
			TreeVo tree = new TreeVo();
			tree.setId(perm.getId());
			tree.setTitle(perm.getName());
			tree.setExpand(false);
			userPermList.stream().forEach((perm2)->{
				if(perm.getId()==perm2.getId())
					tree.setChecked(true);
			});
			treeList.add(tree);
		});
		return ResultVo.success(treeList);
	}

}
